/**
 * @Description: 工具
 * @Author bianpengfei
 * @create 2022/11/23 14:33
 */

const fs = require('fs')
const path = require('path')
const { listToTree, deepClone } = require('sf-utils2')

/**
 * git项目根路径
 * @type {string}
 */
const TOP_ROOT_PATH = path.resolve(__dirname, '..')

/**
 * 是否是生产环境
 * @type {boolean}
 */
const IS_PRO = process.env.NODE_ENV === 'production'

/**
 * 是否开发环境
 * @type {boolean}
 */
const IS_DEV = !IS_PRO

/**
 * 根据路径 获取其下所有子文件包括文件夹路径，返回平面list 和 树状tree
 * @param dir
 * @returns {{tree: *, list: {path: *, relativePath: *, id: *, type: *, parentId: string}[]}}
 */
const getDirChildrenFilesPath = (dir = '') => {
  const itors = (dirName, result = []) => {
    const dirStat = fs.existsSync(dirName) && fs.statSync(dirName)
    if (dirStat) {
      if (dirStat?.isDirectory?.()) {
        fs.readdirSync(dirName).forEach((v) => {
          const absPath = path.join(dirName, v)
          const stat = fs.statSync(path.join(absPath))
          if (stat.isDirectory()) {
            // 是目录，即有children
            result.push({ path: absPath, type: 'dir', rootDir: dir })
            itors(absPath, result)
          } else if (stat.isFile()) {
            // 是文件
            result.push({ path: absPath, type: 'file', rootDir: dir })
          } else {
            result.push({ path: absPath, type: 'unknown', rootDir: dir })
          }
        })
      } else if (dirStat.isFile?.()) {
        result.push({ path: dirName, type: 'file', rootDir: dir })
      }
    }
    return result
  }
  const list = itors(dir).map((v) => {
    const parentPath = path.join('/', v.path.split('/').slice(0, -1).join('/'))
    return {
      path: v.path, // 绝对路径
      parentPath, // 父目录 绝对路径
      ext: path.extname(v.path), // 拓展名
      type: v.type, // 类型 file 或 dir
      relativePath: v.path.replace(dir, '').split('/').filter(Boolean).join('/'), // 相对路径
      rootDir: dir, // 根路径
      isRoot: v.path === dir // 是否根路径文件夹
    }
  })
  const tree = listToTree({
    list: deepClone(list),
    root: dir,
    props: { id: 'path', parentId: 'parentPath', children: 'children' }
  })

  return {
    list: list,
    tree
  }
}

/**
 * 解析环境变量参数 比如 yarn build --baseUrl='xxx'  返回的值是 {baseUrl: 'xxx'}
 * @return {{}}
 */
const parseEnvArgs = () => {
  return process.argv.reduce((pre, cur) => {
    if (cur) {
      const matches = cur.match(/--(\w+)\s*=\s*(\w+)/)
      if (matches && matches[1] && matches[2]) {
        process.env[`${matches[1]}`] = pre[`process.env.${matches[1]}`] = matches[2]
      }
    }
    return pre
  }, {})
}

/**
 * 动态返回环境值
 * @param {*} dev 开发环境
 * @param {*} prod 生产环境
 * @return {*}
 */
function dynamicLoadEnvVars({ dev = undefined, prod = undefined }) {
  return IS_PRO ? prod : dev
}

module.exports = {
  IS_PRO,
  IS_DEV,
  TOP_ROOT_PATH,
  getDirChildrenFilesPath,
  parseEnvArgs,
  dynamicLoadEnvVars
}
